import { App, Modal, Notice } from 'obsidian';
import { ApiClient } from './api-client';
import { ApiResponse, Document } from './types';
import DocumentSharePlugin from './main';
import { UploadModal } from './upload-modal';
import * as QRCode from 'qrcode';

export class DocumentListModal extends Modal {
  private apiClient: ApiClient;
  private plugin: DocumentSharePlugin;
  private documents: Document[] = [];
  private isLoading = false;

  constructor(app: App, apiClient: ApiClient, plugin: DocumentSharePlugin) {
    super(app);
    this.apiClient = apiClient;
    this.plugin = plugin;
  }

  async onOpen() {
    const { contentEl } = this;

    contentEl.empty();
    contentEl.addClass('document-share-list-modal');

    // 标题和刷新按钮
    const headerContainer = contentEl.createDiv({
      cls: 'modal-header-container',
    });
    headerContainer.style.display = 'flex';
    headerContainer.style.justifyContent = 'space-between';
    headerContainer.style.alignItems = 'center';
    headerContainer.style.marginBottom = '20px';

    headerContainer.createEl('h2', { text: '已分享的文档' });

    // 上传本地 Markdown 文件（任意路径）
    const uploadButton = headerContainer.createEl('button', {
      text: '上传本地 Markdown',
    });

    const fileInput = headerContainer.createEl('input') as HTMLInputElement;
    fileInput.type = 'file';
    fileInput.accept = '.md,.markdown,text/markdown';
    fileInput.style.display = 'none';

    uploadButton.addEventListener('click', () => {
      fileInput.click();
    });

    fileInput.addEventListener('change', async () => {
      const file = fileInput.files?.[0];
      if (!file) {
        return;
      }

      try {
        const content = await (file as any).text();
        const defaultTitle = file.name.replace(/\.md$/i, '');
        const pseudoPath = `external:${file.name}`;

        new UploadModal(
          this.app,
          this.plugin,
          pseudoPath,
          defaultTitle,
          content,
        ).open();
      } catch (error: any) {
        new Notice(`读取文件失败: ${error.message || '未知错误'}`);
        console.error('读取本地 Markdown 文件失败:', error);
      } finally {
        // 重置 input，方便下次选择同一个文件
        fileInput.value = '';
      }
    });

    const refreshButton = headerContainer.createEl('button', {
      text: '刷新',
    });
    refreshButton.addEventListener('click', () => {
      this.loadDocuments();
    });

    // 文档列表容器
    const listContainer = contentEl.createDiv({
      cls: 'document-list-container',
    });
    listContainer.style.maxHeight = '500px';
    listContainer.style.overflowY = 'auto';

    // 加载文档列表
    await this.loadDocuments();
  }

  /**
   * 加载文档列表
   */
  private async loadDocuments() {
    if (this.isLoading) {
      return;
    }

    this.isLoading = true;

    const listContainer = this.contentEl.querySelector(
      '.document-list-container',
    ) as HTMLElement;

    if (!listContainer) {
      return;
    }

    // 显示加载中
    listContainer.empty();
    listContainer.createEl('div', {
      text: '正在加载...',
      cls: 'document-list-loading',
    });

    try {
      const response: ApiResponse<Document[]> = await this.apiClient.getDocuments();

      if (response.success && response.data) {
        this.documents = response.data;
        this.renderDocumentList();
      } else {
        listContainer.empty();
        listContainer.createEl('div', {
          text: `加载失败: ${response.message || response.error || '未知错误'}`,
          cls: 'document-list-error',
        });
      }
    } catch (error: any) {
      listContainer.empty();
      listContainer.createEl('div', {
        text: `加载失败: ${error.message}`,
        cls: 'document-list-error',
      });
      console.error('加载文档列表错误:', error);
    } finally {
      this.isLoading = false;
    }
  }

  /**
   * 渲染文档列表
   */
  private renderDocumentList() {
    const listContainer = this.contentEl.querySelector(
      '.document-list-container',
    ) as HTMLElement;

    if (!listContainer) {
      return;
    }

    listContainer.empty();

    if (this.documents.length === 0) {
      listContainer.createEl('div', {
        text: '暂无已分享的文档',
        cls: 'document-list-empty',
      });
      return;
    }

    // 创建文档列表
    this.documents.forEach((document) => {
      const itemEl = listContainer.createDiv({
        cls: 'document-list-item',
      });
      itemEl.style.border = '1px solid var(--background-modifier-border)';
      itemEl.style.borderRadius = '5px';
      itemEl.style.padding = '15px';
      itemEl.style.paddingRight = '130px'; // 为右侧二维码留出空间
      itemEl.style.marginBottom = '10px';
      itemEl.style.position = 'relative'; // 作为二维码定位参考

      // 标题和状态
      const headerEl = itemEl.createDiv({
        cls: 'document-item-header',
      });
      headerEl.style.marginBottom = '10px';

      const titleEl = headerEl.createEl('h3', {
        text: document.title,
      });
      titleEl.style.margin = '0 0 8px 0';
      titleEl.style.fontSize = '16px';

      // 状态标签容器
      const statusContainer = headerEl.createDiv();
      statusContainer.style.display = 'flex';
      statusContainer.style.gap = '5px';
      statusContainer.style.flexWrap = 'wrap';

      // 公开/私密状态
      const visibilityStatusEl = statusContainer.createEl('span', {
        text: document.is_public ? '公开' : '私密',
        cls: 'document-status-badge',
      });
      visibilityStatusEl.style.padding = '2px 8px';
      visibilityStatusEl.style.borderRadius = '3px';
      visibilityStatusEl.style.fontSize = '12px';
      visibilityStatusEl.style.backgroundColor = document.is_public
        ? 'var(--interactive-success)'
        : 'var(--interactive-accent)';
      visibilityStatusEl.style.color = 'white';

      // 过期状态标记
      if (document.is_expired) {
        const expiredStatusEl = statusContainer.createEl('span', {
          text: '已过期',
          cls: 'document-status-badge',
        });
        expiredStatusEl.style.padding = '2px 8px';
        expiredStatusEl.style.borderRadius = '3px';
        expiredStatusEl.style.fontSize = '12px';
        expiredStatusEl.style.backgroundColor = 'var(--text-error)';
        expiredStatusEl.style.color = 'white';
      }

      // 二维码容器（绝对定位在右上角）
      const qrcodeContainer = itemEl.createDiv({
        cls: 'document-qrcode-container',
      });
      qrcodeContainer.style.position = 'absolute';
      qrcodeContainer.style.top = '15px';
      qrcodeContainer.style.right = '15px';
      qrcodeContainer.style.display = 'flex';
      qrcodeContainer.style.flexDirection = 'column';
      qrcodeContainer.style.alignItems = 'center';
      qrcodeContainer.style.padding = '8px';
      qrcodeContainer.style.backgroundColor = 'var(--background-secondary)';
      qrcodeContainer.style.borderRadius = '5px';

      const qrcodeTitle = qrcodeContainer.createEl('div', {
        text: '扫码',
        cls: 'document-qrcode-title',
      });
      qrcodeTitle.style.fontSize = '11px';
      qrcodeTitle.style.fontWeight = 'bold';
      qrcodeTitle.style.marginBottom = '6px';
      qrcodeTitle.style.color = 'var(--text-normal)';

      const qrcodeCanvas = qrcodeContainer.createEl('canvas', {
        cls: 'document-qrcode-canvas',
      });

      const viewUrl = this.apiClient.getDocumentViewUrl(document.uuid);

      // 生成二维码（小尺寸）
      QRCode.toCanvas(qrcodeCanvas, viewUrl, {
        width: 100,
        margin: 1,
        color: {
          dark: '#000000',
          light: '#FFFFFF',
        },
      }).catch((error: Error) => {
        console.error('生成二维码失败:', error);
        qrcodeContainer.createEl('div', {
          text: '生成失败',
          cls: 'document-qrcode-error',
        }).style.color = 'var(--text-error)';
      });

      const qrcodeHint = qrcodeContainer.createEl('div', {
        text: '手机扫码',
        cls: 'document-qrcode-hint',
      });
      qrcodeHint.style.fontSize = '10px';
      qrcodeHint.style.marginTop = '4px';
      qrcodeHint.style.color = 'var(--text-muted)';

      // 详细信息
      const infoEl = itemEl.createDiv({
        cls: 'document-item-info',
      });
      infoEl.style.fontSize = '13px';
      infoEl.style.color = 'var(--text-muted)';
      infoEl.style.marginBottom = '10px';

      infoEl.createEl('div', {
        text: `作者: ${document.author}`,
      });
      infoEl.createEl('div', {
        text: `主题: ${document.theme}`,
      });

      // 私密文档显示密码
      if (!document.is_public && document.password) {
        infoEl.createEl('div', {
          text: `密码: ${document.password}`,
        });
      }

      infoEl.createEl('div', {
        text: `访问次数: ${document.views}`,
      });
      infoEl.createEl('div', {
        text: `创建时间: ${new Date(document.created_at).toLocaleString('zh-CN')}`,
      });
      if (document.expires_at) {
        const expiresEl = infoEl.createEl('div', {
          text: `过期时间: ${new Date(document.expires_at).toLocaleString('zh-CN')}`,
        });
        if (document.is_expired) {
          expiresEl.style.color = 'var(--text-error)';
          expiresEl.style.fontWeight = 'bold';
        }
      } else {
        infoEl.createEl('div', {
          text: `过期时间: 永久有效`,
        });
      }

      // 操作按钮
      const actionsEl = itemEl.createDiv({
        cls: 'document-item-actions',
      });
      actionsEl.style.display = 'flex';
      actionsEl.style.gap = '10px';

      // 复制链接按钮
      const copyButton = actionsEl.createEl('button', {
        text: '复制链接',
      });
      copyButton.addEventListener('click', async () => {
        await navigator.clipboard.writeText(viewUrl);
        new Notice('链接已复制到剪贴板');
      });

      // 在浏览器中打开
      const openButton = actionsEl.createEl('button', {
        text: '在浏览器中打开',
      });
      openButton.addEventListener('click', () => {
        window.open(viewUrl, '_blank');
      });

      // 定位源文件按钮
      const locateButton = actionsEl.createEl('button', {
        text: '定位源文件',
      });
      locateButton.addEventListener('click', () => {
        this.locateSourceFile(document.title);
      });

      // 删除按钮
      const deleteButton = actionsEl.createEl('button', {
        text: '删除',
        cls: 'mod-warning',
      });
      deleteButton.addEventListener('click', () => {
        this.deleteDocument(document);
      });
    });
  }

  /**
   * 定位源文件
   */
  private locateSourceFile(title: string) {
    // 搜索与文档标题匹配的文件
    const files = this.app.vault.getMarkdownFiles();

    // 尝试精确匹配文件名
    let matchedFile = files.find((file) => file.basename === title);

    // 如果没有精确匹配,尝试模糊匹配
    if (!matchedFile) {
      matchedFile = files.find((file) =>
        file.basename.toLowerCase().includes(title.toLowerCase()),
      );
    }

    if (matchedFile) {
      // 在 Obsidian 中打开文件
      this.app.workspace.openLinkText(matchedFile.path, '', true);
      new Notice(`已定位到文件: ${matchedFile.path}`);
      this.close();
    } else {
      new Notice(
        `未找到匹配的源文件: ${title}\n可能文件已被删除或重命名`,
      );
    }
  }

  /**
   * 删除文档
   */
  private async deleteDocument(document: Document) {
    const confirmed = confirm(
      `确定要删除文档 "${document.title}" 吗？\n\n` +
      `此操作不可恢复，但不会删除本地的 Markdown 文件。`,
    );

    if (!confirmed) {
      return;
    }

    new Notice('正在删除文档...');

    try {
      const response = await this.apiClient.deleteDocument(document.uuid);

      if (response.success) {
        new Notice('文档已删除');

        // 从列表中移除
        this.documents = this.documents.filter(
          (d) => d.uuid !== document.uuid,
        );

        // 从本地映射中移除（遍历所有文件路径查找该 UUID）
        for (const filePath in this.plugin.documentMapping) {
          await this.plugin.removeDocumentMapping(filePath, document.uuid);
        }

        // 刷新文件装饰器
        this.plugin.refreshFileDecorations();

        // 重新渲染列表
        this.renderDocumentList();
      } else {
        new Notice(
          `删除失败: ${response.message || response.error || '未知错误'}`,
        );
      }
    } catch (error: any) {
      new Notice(`删除失败: ${error.message}`);
      console.error('删除文档错误:', error);
    }
  }

  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
}
